package com.yy.jhl.api;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.google.gson.Gson;
import com.yy.common.R;
import com.yy.common.baseapp.AppManager;
import com.yy.common.baseapp.BaseApplication;
import com.yy.common.basebean.BaseResponse;
import com.yy.common.baserx.ServerException;
import com.yy.common.commonutils.LogUtils;
import com.yy.common.commonutils.NetWorkUtils;
import com.yy.common.commonutils.SPUtils;
import com.yy.common.commonutils.StringUtil;
import com.yy.common.commonutils.ToastUitl;
import com.yy.common.commonwidget.LoadingDialog;
import com.yy.jhl.app.AppConstant;
import com.yy.jhl.app.MyApplication;
import com.yy.jhl.bean.ErrorInfo;
import com.yy.jhl.interfaces.CommonCallBack;
import com.yy.jhl.ui.user.activity.LoginSelectActivity;
import com.yy.jhl.util.DialogUtil;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * des:订阅封装
 */
public abstract class RxSubscriber<T> extends Subscriber<T> {

    private Context mContext;
    private String msg;
    private boolean showDialog=true;
    private boolean netWorkErrorToast=true;
    private boolean isShowLogin=true;

    /**
     * 是否显示浮动dialog
     */
    public void showDialog() {
        this.showDialog= true;
    }
    public void hideDialog() {
        this.showDialog= true;
    }

    public RxSubscriber(Context context, String msg, boolean showDialog) {
        this.mContext = context;
        this.msg = msg;
        this.showDialog=showDialog;
    }
//    public RxSubscriber(Context context,boolean showDialog,boolean netWorkErrorToast) {
//        this.mContext = context;
//        this.showDialog=showDialog;
//        this.netWorkErrorToast=netWorkErrorToast;
//    }
    public RxSubscriber(Context context) {
        this(context, BaseApplication.getAppContext().getString(R.string.loading),true);
    }
    public RxSubscriber(Context context, boolean showDialog,boolean isShowLogin ) {
        this(context, BaseApplication.getAppContext().getString(R.string.loading),showDialog);
        this.isShowLogin = isShowLogin;
    }
    public RxSubscriber(Context context, boolean showDialog) {
        this(context, BaseApplication.getAppContext().getString(R.string.loading),showDialog);
    }

    @Override
    public void onCompleted() {
        if (showDialog)
            LoadingDialog.cancelDialogForLoading();
    }
    @Override
    public void onStart() {
        super.onStart();
        if (showDialog) {
            try {
                LoadingDialog.showDialogForLoading((Activity) mContext,msg,false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void onNext(T t) {
        if (showDialog)LoadingDialog.cancelDialogForLoading();
        ResponseBody responseBody = (ResponseBody) t;
        String result = "";
        try {
            result = responseBody.string();
        } catch (IOException e) {
            e.printStackTrace();
        }
            LogUtils.loge("RESULT",result);
            if (result.equals("[]") || result.equals("{}")|| result.equals("")){
                _onNext(result);
            }else {
                ErrorInfo errorInfo = null;
                try {
                    errorInfo =  new Gson().fromJson(result,ErrorInfo.class);
                    if (errorInfo != null){
                        if (errorInfo.getCode() != null){
                            String errorDesc = errorInfo.getMsg().toString();
                            if (errorInfo.getCode().equals("10010")){
                                if (isShowLogin){
                                    ToastUitl.showShort(errorDesc);
                                    MyApplication.getInstance().clearData();
                                    AppManager.getAppManager().finishAllActivity();
                                    mContext.startActivity(new Intent(mContext,LoginSelectActivity.class));
                                }else {
                                    SPUtils.setSharedStringData(mContext, AppConstant.SP_KEY_TOKEN_LINSHI, errorInfo.getToken());
                                    onError(errorDesc);
                                }
                            }else if (errorInfo.getCode().equals("10403")){
                                //未认证提示
                                DialogUtil.showOnlyEnsureDialogView(mContext, "亲，认证后可以获取更多的操作权限，快去网页版认证哦！", new CommonCallBack() {
                                    @Override
                                    public void getCallBack() {

                                    }
                                });
                            }else {
                                onError(errorDesc);
                            }
                        }else {
                            _onNext(result);
                        }
                    }else {
                        onError("数据解析错误");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    _onNext(result);
                }


            }

    }
    @Override
    public void onError(Throwable e) {
        if (showDialog)
            LoadingDialog.cancelDialogForLoading();
        e.printStackTrace();
        //网络
        if (!NetWorkUtils.isNetConnected(BaseApplication.getAppContext())) {
            onNetError(BaseApplication.getAppContext().getString(R.string.no_net));
        }
        //服务器
        else if (e instanceof ServerException) {
            onError(e.getMessage());
        }
        //其它
        else {
            onError(BaseApplication.getAppContext().getString(R.string.net_error));
        }
    }

    /**
     * 处理error
     * @param error
     */
    private void onError(String error){
        if(showDialog && !StringUtil.isEmpty(error))ToastUitl.showShort(error);
        _onError(error);
    }

    /**
     * 处理error
     * @param error
     */
    private void onNetError(String error){
        if(netWorkErrorToast)ToastUitl.showShort(error);
        _onError(error);
    }

    protected abstract void _onNext(String t);

    protected abstract void _onError(String message);

}
